import React, { Component } from 'react'
import { nanoid } from 'nanoid'
import './index.css'

export default class TodoListCLassTest extends Component {
  state = {
    todos: [
      { id: '001', name: '吃饭', done: true },
      { id: '002', name: '睡觉', done: false },
      { id: '003', name: '打代码', done: true },
    ],
    arr: ['完成', '未完成', '全部'],
    currentActive: 2,
    showData: [],
  }

  render() {
    let { arr, currentActive } = this.state
    return (
      <div>
        <div>
          <input
            type="text"
            ref={(v) => (this.todoInput = v)}
            onKeyUp={this.enterAdd}
          />{' '}
          <button onClick={this.add}>添加</button>
        </div>
        <ul onClick={this.changeDone}>
          {this.showData.map((v) => {
            return (
              <li key={v.id} data-id={v.id} className={v.done ? 'done' : ''}>
                {v.name}
              </li>
            )
          })}
        </ul>
        <div>
          {arr.map((v, index) => {
            return (
              <button
                key={index}
                onClick={() => this.setState({ currentActive: index })}
                className={index === currentActive ? 'active' : ''}
              >
                {v}
              </button>
            )
          })}
        </div>
      </div>
    )
  }

  // 改变状态
  changeDone = (e) => {
    let id = e.target.dataset.id
    let { todos } = this.state
    todos = todos.map((v) => {
      if (v.id === id) {
        v.done = !v.done
      }
      return v
    })
    this.setState({ todos })
  }

  add = () => {
    this.setState({
      todos: [
        ...this.state.todos,
        { id: nanoid(), name: this.todoInput.value },
      ],
    })
    this.todoInput.value = ''
  }

  enterAdd = (e) => {
    if (e.keyCode === 13) {
      this.setState({
        todos: [
          ...this.state.todos,
          { id: nanoid(), name: this.todoInput.value },
        ],
      })
      this.todoInput.value = ''
    }
  }

  get showData() {
    let { todos, currentActive } = this.state
    switch (currentActive) {
      case 0:
        return todos.filter((v) => v.done === true)
      case 1:
        return todos.filter((v) => v.done !== true)
      case 2:
        return todos
    }
  }
}
